from PySide6.QtWidgets import (QStackedLayout,
                               QWidget,
                               QVBoxLayout,
                               QStatusBar,
                               QLabel,
                               QListView, QListWidget)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt, Signal, QStringListModel
from func import Function
from threading import Thread
import time
import re
import threading
from doc2docx import convert
from docx import Document


class Tab1(QWidget):
    deleteandaddtab = Signal()
    tab5addly5 = Signal()
    lyt4 = Signal(list, list)
    ly3 = Signal()
    def __init__(self):
        super().__init__()
        self.lt5 = QVBoxLayout()
        self.fc = Function()
        self.wordlist = []
        self.font = QFont()
        self.font.setFamily("Arial")
        self.font.setPointSize(15)
        self.font2 = QFont()
        self.font2.setPointSize(15)
        self.layout = QStackedLayout()
        self.widgetlayout = QVBoxLayout()
        self.label1 = QLabel(self)
        self.label1.setText("Drop in or right click to paste Word documents in this window")
        self.label1.setFont(self.font2)
        self.widget = QListWidget()
        self.widget.setLayout(self.widgetlayout)
        self.layout.addWidget(self.label1)
        self.layout.addWidget(self.widget)
        self.setLayout(self.layout)
        self.layout.setCurrentWidget(self.label1)
        self.setAcceptDrops(True)
        self.statusbar = QStatusBar(self.widget)
        self.widgetlayout.addWidget(self.statusbar, 0, Qt.AlignBottom)

    def setcurrentwidget(self):
        if self.layout.currentWidget() == self.label1:
            self.layout.setCurrentWidget(self.widget)

    def controlprint(self, dual):
        itemlist = []
        duale = len(dual)
        for i in range(duale):
            split = dual[i][0].split('\t')
            count = 0
            count2 = 0
            for j in split[0]:
                if re.match(r'^[\u4e00-\u9fa5]+$', j):
                    count += 1
            for j in split[1]:
                if re.match(r'^[\u4e00-\u9fa5]+$', j):
                    count2 += 1
            # count1和count2分别是两个词语中汉字的个数
            len1 = len(split[0]) - count + count * 1.5
            len2 = len(split[1]) - count2 + count2 * 1.5
            len1_ = len(split[0]) - count + count * 3
            len2_ = len(split[1]) - count2 + count2 * 3
            # len1和len2分别是两个字符串的实际近似长度，一个汉字长约一个字母的1.5倍
            s1 = split[0] + ' ' * int(14 - len1)
            s2 = ' ' * int(14 - len2) + split[1]
            s1_ = split[0] + ' ' * int(30 - len1_)
            s2_ = ' ' * int(30 - len2_) + split[1]
            cover1 = f'{i + 1:<10}{s1}\t{dual[i][1]:>6}\t{s2}'
            cover2 = f'{i + 1:<10}{s1_}{dual[i][1]:>6}{s2_}'
            if dual[i][1] != 0:
                itemlist.append(cover2)
                print(cover1)
                print('----------------------------------------------------------------')
        return itemlist

    def wordlistop(self, wl):
        for i in wl:
            spilt = i.split('/')
            p = spilt[-1]
            spt = p.split('.')
            # print(spt[0])
            if spt[1] == 'doc':
                le = len(p)
                s1 = i[:-le]
                convert(i)
                i_ = s1 + spt[0] + '.docx'
                if i_ not in wl:
                    wl.append(i_)
                continue
            else:
                self.fc.w_l.append(spt[0])
                doc0 = Document(i)
            par = ''
            for para in doc0.paragraphs:
                if para.text != '\r':
                    par += para.text
            thre = Thread(target=self.fc.validculculation, args=(par, spt[0]))
            # 对每个打开的word文档开启多线程计算
            thre.start()
            thre.join()


    def enterpressinit(self):
        self.fc.contentlist.clear()
        self.fc.top.clear()
        self.fc.hvl.clear()
        self.fc.highrelativelist.clear()
        self.fc.dischart.clear()
        self.fc.w_l.clear()
        for i in range(self.lt5.count()):
            self.lt5.itemAt(i).widget().deleteLater()
        self.deleteandaddtab.emit()

    def ranklist(self):
        dual = self.fc.dualpair
        itemlist = self.controlprint(dual)
        # 将多对有相关性的文件列表创建成格式化的列表
        le_ = len(itemlist)
        if le_ != 0:
            lm = QStringListModel()
            lv = QListView()
            lm.setStringList(itemlist)
            lv.setModel(lm)
            lv.setFont(self.font)
            self.lt5.addWidget(lv)
            self.tab5addly5.emit()

    def removedoc(self, path):
        spilt = path.split('/')
        p = spilt[-1]
        spt = p.split('.')
        if spt[1] == 'docx':
            return path

    def printchart(self, chart):
        for i in chart:
            for j in i:
                print(f'{j:>8}', end=" ")
            print()
        print('----------------------------------------------------------------')

    def enterPressed(self):
        start = time.time()
        # 开始计时
        print('enter')
        self.enterpressinit()
        wl = self.wordlist.copy()
        self.wordlistop(wl)
        # 读取每个文件
        wl = list(filter(self.removedoc, wl))
        # 删除所有doc文件
        self.fc.inidischt(wl)
        # 表格初始化
        self.ranklist()
        # 通过判断是否存在多对高相关性文件来控制是否显示tab5
        chart = self.fc.dischart
        self.printchart(chart)
        wl_ = self.fc.w_l
        wlen = len(wl)
        for i in range(wlen):
            print(f'{i + 1:<6}{wl_[i]}')
        print('----------------------------------------------------------------')
        self.lyt4.emit(chart, wl_)
        self.statusbar.showMessage("Double click to view condence words")
        finish = time.time()
        tt = round(finish - start, 3)
        print(f'running time is {tt} seconds')

    def deletePressed(self):
        print('delete')
        wile_ = self.widget.count()
        for i in range(wile_):
            if self.widget.item(i).isSelected():
                self.widget.takeItem(i)
                self.wordlist.pop(i)
        self.fc.w_l.clear()

    def getpath(self, path):
        self.wordlist.append(path)
        print(path)
        slpit = path.split('/')
        p = slpit[-1]
        self.widget.addItem(p)
        self.statusbar.showMessage("Enter while all files are ready")
        if self.layout.currentWidget() != self.widget:
            self.layout.setCurrentWidget(self.widget)

    def miahasurls(self, mia):
        for url in mia.urls():
            path = url.toLocalFile()
            if path not in self.wordlist:
                self.getpath(path)
            else:
                print("already get this file")
